package game.engine.base

import java.util.*
import kotlin.collections.ArrayList

class Scheduler(val scene: Scene) {

    private val frameFuncLst = LinkedList<FrameFunc>()

    private val newAddLst = ArrayList<FrameFunc>()

    //
    private var inSchedule = false

    fun update(dt:Float){
        inSchedule = true

        // 执行事件
        val iter = frameFuncLst.iterator()
        while (iter.hasNext()) {
            val func = iter.next()
            if (func.completed){
                iter.remove()
            }else{
                if (scene.willDestroy){
                    return
                }
                func.execute(dt)
                if (func.completed) {
                    iter.remove()
                }
            }
        }
        inSchedule = false

        if (newAddLst.size > 0){
            frameFuncLst.addAll(newAddLst)
            newAddLst.clear()
        }
    }

    // 添加一个 frameFunc
    fun addFrameFunc(frameFunc:FrameFunc){
        if (inSchedule){
            newAddLst.add(frameFunc)
        }else{
            frameFuncLst.add(frameFunc)
        }
    }

    // 删除一个 frameFunc
    fun removeFrameFunc(frameFunc: FrameFunc){
        frameFunc.completed = true
    }

    fun release(){
        newAddLst.clear()
        frameFuncLst.clear()
        inSchedule = false
    }
}